package view
{
	import com.greensock.TweenLite;
	import com.greensock.easing.Back;
	
	import data.Globals;
	
	import flash.display.InteractiveObject;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.text.TextField;
	import flash.text.TextFormat;
	
	public class AlertView extends Sprite
	{
		private var txt:TextField;
		
		private var yesBtn:InteractiveObject;
		
		private var noBtn:InteractiveObject;
		
        public static const YES:String = "yes";
		
		public static const NO:String = "no";
		
		private var callback:Function;
		
		private var yesPosition:Point;
		
		private var noPosition:Point;

		private var str:String;
		
	    private var _showNo:Boolean  =true;
		
		public function AlertView()
		{
			super();
			var maskSp:Sprite = new Sprite();
			maskSp.graphics.beginFill(0x000000,0.5);
			maskSp.graphics.drawRect(-Globals.stage_width/2,-Globals.stage_height/2,Globals.stage_width,Globals.stage_height);
			maskSp.graphics.endFill();
			this.addChild(maskSp);
			
			var alert:AlertCls = new AlertCls();
			this.addChild(alert);
			txt = alert.AlertTxt;
			yesBtn = alert.yes;
			noBtn = alert.no;
			yesPosition = new Point(yesBtn.x,yesBtn.y);
			noPosition = new Point(noBtn.x,noBtn.y);
			this.x = Globals.stage_width/2;
			this.y = Globals.stage_height/2;
		}
		
		public function setTxt(str:String,tformat:TextFormat = null):void{
			txt.text = str;
			if(tformat){
				txt.setTextFormat(tformat);		
			}
		}
		
		/**
		 * 回调函数 
		 * @param cb
		 */
		public function show(cb:Function,showYes:Boolean,showNo:Boolean):void{
			this.alpha = 0;
			this.scaleX = this.scaleY = 0;
			_showNo = showNo;
			callback = cb;
			setBtn(showYes,showNo);
			TweenLite.to(this, 1, {x:this.x, y:this.y, scaleX:1, scaleY:1, alpha:1, ease:Back.easeOut});
			yesBtn.addEventListener(MouseEvent.CLICK,clickBtn);
			noBtn.addEventListener(MouseEvent.CLICK,clickBtn);
		}
		
		private function setBtn(showYes:Boolean,showNo:Boolean):void{
			if(showYes&&showNo){
				yesBtn.x = yesPosition.x;
				yesBtn.y = yesPosition.y;
				noBtn.visible = true;
			}else if(showYes&&!showNo){
				yesBtn.x = this.width/2;
				noBtn.visible = false;
			}
		}
		
		private function clickBtn(event:MouseEvent):void
		{
			str = event.target == yesBtn ? YES : NO;
			hide();
		}
		
		public function hide():void{
			TweenLite.to(this, 1, {x:this.x, y:this.y, scaleX:0, scaleY:0, alpha:0, ease:Back.easeOut ,onComplete:remove});
		}
		
		private function remove():void{
			if(this.parent){
				this.parent.removeChild(this);
			}
			if(!_showNo){
				callback();
			}else{
				callback(str);
			}
		}
	}
}